// 全局状态变量
let currentSentenceIndex = 0;
let currentWordIndex = 0;
let score = 0;
let scoreElement = null;
let reviewMode = false; // 是否处于复习模式
let reviewSentenceIds = []; // 需要复习的句子ID列表
let audioSpeed = 1.0; // 音频播放速度，默认为1.0倍
const audioCache = new Map(); // 音频缓存对象
const PRELOAD_DEPTH = 2; // 预加载深度：当前和下一个句子
const MAX_LEARNING_TIME = 30000; // 最大学习时间(毫秒) - 30秒
let learningTimer = null; // 学习计时器

// DOM元素
const wordPracticeSection = document.getElementById('wordPractice');
const sentencePracticeSection = document.getElementById('sentencePractice');
const wordOptionsContainer = document.getElementById('wordOptions');
const sentenceOptionsContainer = document.getElementById('sentenceOptions');
const playWordBtn = document.getElementById('playWordBtn');
const playSentenceBtn = document.getElementById('playSentenceBtn');
const feedbackElement = document.getElementById('feedback');
const nextBtn = document.getElementById('nextBtn');
let progressBar = document.getElementById('progressBar');
const scoreValue = document.getElementById('scoreValue');

// 更新积分显示
function updateScoreDisplay() {
    scoreValue.textContent = score;
    // 添加积分变化动画
    scoreValue.classList.add('correct-animation');
    setTimeout(() => {
        scoreValue.classList.remove('correct-animation');
    }, 500);
}

// 创建金币飞行动画（弧线轨迹与增强旋转）
function createCoinAnimation(x, y, onComplete) {
    const coin = document.createElement('div');
    coin.className = 'coin-animation';
    coin.innerHTML = '<div class="coin"></div>';
    coin.style.left = `${x}px`;
    coin.style.top = `${y}px`;
    document.body.appendChild(coin);

    // 获取钱袋子图标的位置
    const coinIcon = document.querySelector('.coin-icon');
    const coinIconRect = coinIcon.getBoundingClientRect();
    const targetX = coinIconRect.left + coinIconRect.width / 2;
    const targetY = coinIconRect.top + coinIconRect.height / 2;

    const coinElement = coin.querySelector('.coin');
    coinElement.style.width = '30px';
    coinElement.style.height = '30px';

    // 动画参数
    const duration = 1200; // 动画持续时间（毫秒）- 整体速度调快
    const start = performance.now();
    const dx = targetX - x;
    const dy = targetY - y;

    // 动画函数
    function animate(timestamp) {
        const elapsed = timestamp - start;
        const progress = Math.min(elapsed / duration, 1);

        // 使用自定义缓动函数实现更优雅拟真的动画插值
        // 先加速后减速的平滑曲线 (easeInOutQuad的变种)
        let easeProgress;
        if (progress < 0.5) {
            easeProgress = 2 * progress * progress;
        } else {
            easeProgress = -1 + (4 - 2 * progress) * progress;
        }

        // 计算带轻微弧度的轨迹
        const arcHeight = Math.min(Math.abs(dx), Math.abs(dy)) * 0.2; // 弧线高度
        const arcOffset = Math.sin(progress * Math.PI) * arcHeight; // 正弦曲线偏移
        const currentX = x + dx * easeProgress;
        const currentY = y + dy * easeProgress - arcOffset;

        // 更新金币位置和旋转
        coinElement.style.transform = `translate(${currentX - x}px, ${currentY - y}px)`;

        // 接近目标时缩小并淡出
        let scale = 1;
        let opacity = 1;
        if (progress > 0.7) {
            // 最后30%的动画开始缩小淡出
            const fadeProgress = (progress - 0.7) / 0.3;
            scale = 1 - fadeProgress * 0.8; // 保留20%大小
            opacity = 1 - fadeProgress;
        }
        coinElement.style.opacity = opacity;
        coinElement.style.transform += ` scale(${scale});;;;;`;

        if (progress < 1) {
            requestAnimationFrame(animate);
        } else {
            // 动画结束后移除元素
            document.body.removeChild(coin);
            // 添加积分跳动动画
            const scoreElement = document.getElementById('scoreValue');
            scoreElement.classList.add('pulse-animation');
            setTimeout(() => {
                scoreElement.classList.remove('pulse-animation');
                // 动画完全结束后调用回调函数
                if (typeof onComplete === 'function') {
                    onComplete();
                }
            }, 300);
        }
    }

    // 开始动画
    requestAnimationFrame(animate);
}

// 初始化应用
let pendingAudio = null;
// 处理音频播放错误
function handleAudioPlayError(e, buttonElement, audioPath, callback) {
    console.error('播放音频失败:', e);
    if (buttonElement) {
        buttonElement.classList.remove('playing');
        buttonElement.disabled = false;
    }
    window.currentAudio = null;
    audioCache.delete(audioPath);
    if (callback) callback();
}

function initApp() {
    // 确保progressBar元素已加载
    progressBar = document.getElementById('progressBar');
    if (!progressBar) {
        setTimeout(initApp, 100);
        return;
    }
    
    // 初始化进度条
    updateProgress();
    // 等待ProgressData加载完成
    if (typeof ProgressData === 'undefined') {
        setTimeout(initApp, 100);
        return;
    }

    // 检查是否有需要复习的句子
    reviewSentenceIds = ProgressData.getSentencesToReview();
    reviewMode = reviewSentenceIds.length > 0;

    console.log('复习模式:', reviewMode);
    console.log('需要复习的句子数:', reviewSentenceIds.length);

    // 从ProgressData加载积分
    score = ProgressData.getScore() || 0;
    // 初始化积分显示
    updateScoreDisplay();

    // 从ProgressData加载学习进度
    const savedProgress = ProgressData.getCurrentProgress();
    currentSentenceIndex = savedProgress.sentenceIndex || 0;
    currentWordIndex = savedProgress.wordIndex || 0;

    // 添加用户交互监听器
    document.addEventListener('click', function userInteractionHandler() {
        hasUserInteracted = true;
        document.removeEventListener('click', userInteractionHandler);

        // 如果有等待播放的音频，立即播放
        if (pendingAudio) {
            const { audio, buttonElement, callback } = pendingAudio;
            pendingAudio = null;
            audio.play().catch(e => {
                handleAudioPlayError(e, buttonElement, audio.src, callback);
            });
        }
    }, { once: true });

    // 开始相应句子的单词练习
    startWordPractice();

    // 添加事件监听器
    playWordBtn.addEventListener('click', playCurrentWord);
    playSentenceBtn.addEventListener('click', playCurrentSentence);
    nextBtn.addEventListener('click', goToNextItem);
}

// 开始单词练习
function startWordPractice() {
    const currentSentence = sentenceData[currentSentenceIndex];
    const currentWord = currentSentence.words[currentWordIndex];

    // 开始记录单词学习时间
    if (typeof ProgressData !== 'undefined') {
        ProgressData.startWordLearning(currentWord);
    }

    // 设置30秒学习计时器
    if (learningTimer) {
        clearTimeout(learningTimer);
    }
    learningTimer = setTimeout(() => {
        console.log('单词学习时间已达到30秒上限');
        // 记录学习时间已达上限，但不自动跳转
        // 注意：实际学习时长已在checkWordAnswer中记录，这里不再重复记录
        learningTimer = null;
    }, MAX_LEARNING_TIME);

    // 预加载音频资源
    preloadAudioResources();

    // 生成单词选项
    const allWords = [...new Set(sentenceData.flatMap(item => item.words))];
    const wordOptions = generateWordOptions(currentWord, allWords);

    // 清空并生成选项UI
    wordOptionsContainer.innerHTML = '';
    wordOptions.forEach(word => {
        const optionElement = document.createElement('div');
        optionElement.className = 'option';
        optionElement.textContent = word;
        optionElement.addEventListener('click', () => checkWordAnswer(word));
        wordOptionsContainer.appendChild(optionElement);
    });

    // 自动播放当前单词音频
    playCurrentWord();
}

// 预加载单词音频
function preloadWordAudio(sentenceIndex) {
    if (!sentenceData[sentenceIndex]) return;
    sentenceData[sentenceIndex].words.forEach(word => {
        const audioPath = `voice/words/${word.toLowerCase()}.mp3`;
        if (!audioCache.has(audioPath)) {
            const audio = new Audio(audioPath);
            audioCache.set(audioPath, audio);
        }
    });
}

// 预加载句子音频
function preloadSentenceAudio(sentenceIndex) {
    if (!sentenceData[sentenceIndex]) return;
    const sentenceId = sentenceData[sentenceIndex].id;
    const audioPath = `voice/sentences/sentence_${sentenceId}.mp3`;
    if (!audioCache.has(audioPath)) {
        const audio = new Audio(audioPath);
        audioCache.set(audioPath, audio);
    }
}

// 批量预加载音频
function preloadAudioResources() {
    // 预加载当前和下一个句子的音频
    for (let i = 0; i < PRELOAD_DEPTH; i++) {
        const sentenceIndex = currentSentenceIndex + i;
        if (sentenceIndex < sentenceData.length) {
            preloadWordAudio(sentenceIndex);
            preloadSentenceAudio(sentenceIndex);
        }
    }
}

// 播放当前单词
function playCurrentWord() {
    const currentWord = sentenceData[currentSentenceIndex].words[currentWordIndex];
    enableOptions(wordOptionsContainer);
    const audioPath = `voice/words/${currentWord.toLowerCase()}.mp3`;
    // 使用缓存的音频或加载新音频
    playAudioFile(audioPath, playWordBtn, () => {});
}

// 播放当前句子
function playCurrentSentence() {
    const sentenceId = sentenceData[currentSentenceIndex].id;
    const audioPath = `voice/sentences/sentence_${sentenceId}.mp3`;
    playAudioFile(audioPath, playSentenceBtn);
}

// 设置音频播放速度
function setAudioSpeed(speed) {
    audioSpeed = speed;
    
    // 更新速度菜单中的当前速度显示
    const currentSpeedDisplay = document.getElementById('currentSpeed');
    if (currentSpeedDisplay) {
        currentSpeedDisplay.textContent = speed + 'x';
    }
    
    // 更新速度选项的样式
    document.querySelectorAll('.speed-option').forEach(opt => {
        if (parseFloat(opt.dataset.speed) === speed) {
            opt.classList.add('active');
        } else {
            opt.classList.remove('active');
        }
    });
}

// 播放音频文件
function playAudioFile(audioPath, buttonElement, callback) {
    // 停止任何正在进行的音频
    if (window.currentAudio) {
        window.currentAudio.pause();
        window.currentAudio = null;
    }

    // 移除所有按钮的播放状态
    playWordBtn.classList.remove('playing');
    playSentenceBtn.classList.remove('playing');
    // 确保所有按钮都是可点击的
    playWordBtn.disabled = false;
    playSentenceBtn.disabled = false;

    // 激活当前按钮的播放状态
    if (buttonElement) {
        buttonElement.classList.add('playing');
        // 禁用当前按钮
        buttonElement.disabled = true;
    }

    // 获取缓存的音频或创建新实例
    let audio = audioCache.get(audioPath);
    if (!audio) {
        audio = new Audio(audioPath);
        audioCache.set(audioPath, audio);
    } else {
        // 重置音频播放位置
        audio.currentTime = 0;
    }

    window.currentAudio = audio;

    // 设置音频播放速度
    audio.playbackRate = audioSpeed;

    // 音频播放结束时移除播放状态并启用按钮
    audio.onended = function() {
        if (buttonElement) {
            buttonElement.classList.remove('playing');
            // 启用按钮
            buttonElement.disabled = false;
        }
        window.currentAudio = null;
        if (callback) callback();
    };

    // 音频播放出错时处理并启用按钮
    audio.onerror = function() {
        console.error('播放音频失败:', audioPath);
        if (buttonElement) {
            buttonElement.classList.remove('playing');
            // 启用按钮
            buttonElement.disabled = false;
        }
        window.currentAudio = null;
        // 从缓存中移除错误的音频
        audioCache.delete(audioPath);
        // 检查是否是用户交互问题
        showInteractionPromptIfNeeded();
        if (callback) callback();
    };

    // 播放音频 - 移除用户交互检查
    audio.play().catch(e => {
        handleAudioPlayError(e, buttonElement, audioPath, callback);
    });
}

// 移除用户交互提示相关函数

// 保留函数定义以避免引用错误
function speakText(text, callback) {
    console.warn('speakText函数已被弃用，请使用playAudioFile函数代替。');
    if (callback) callback();
}

function fallbackSpeakText(text) {
    console.warn('fallbackSpeakText函数已被弃用，请使用playAudioFile函数代替。');
}

// 检查单词答案
function checkWordAnswer(selectedWord) {
    // 先定义currentWord变量
    const currentWord = sentenceData[currentSentenceIndex].words[currentWordIndex];
    const isTimeout = selectedWord === null;
    const isCorrect = !isTimeout && selectedWord === currentWord;
    
    // 清除学习计时器并记录实际学习时长
    if (learningTimer) {
        clearTimeout(learningTimer);
        learningTimer = null;
        // 记录实际学习时长
        if (typeof ProgressData !== 'undefined') {
            ProgressData.finishWordLearning(currentWord, isCorrect);
        }
    }
    
    // 结束记录单词学习时间并保存记录
    if (typeof ProgressData !== 'undefined') {
        ProgressData.finishWordLearning(currentWord, isCorrect);
    }
    
    // 记录学习事件
    if (typeof LearningStats !== 'undefined') {
        LearningStats.recordLearningEvent(isCorrect);
    }
    
    const sentenceId = sentenceData[currentSentenceIndex].id;

    // 播放音效
const audio = new Audio(isCorrect ? 'audio/word_correct.mp3' : 'audio/word_wrong.mp3');
if (!isCorrect && !isTimeout) {
    // 禁用所有选项
    disableOptions(wordOptionsContainer);
}
new Promise((resolve) => {
    audio.addEventListener('ended', resolve, { once: true });
    audio.play().catch(e => {
        console.log('播放音效失败:', e);
        resolve();
    });
}).then(() => {
    if (!isCorrect && !isTimeout) {
        // 音效播放完毕后播放错误单词发音
        playAudioFile(`voice/words/${selectedWord}.mp3`, null, () => {
            // 发音结束后启用选项
            enableOptions(wordOptionsContainer);
    });
} else if (isTimeout) {
    console.log('单词学习超时');
}
});
// 显示反馈
showFeedback(isCorrect);

// 高亮选中的选项
highlightSelectedOption(wordOptionsContainer, selectedWord, isCorrect);

// 更新学习进度记录
ProgressData.updateSentenceRecord(sentenceId, isCorrect);

// 更新进度
updateProgress();

// 如果正确，增加分数
if (isCorrect) {
        // 禁用所有选项
        disableOptions(wordOptionsContainer);
        // 保存当前学习进度
        ProgressData.setCurrentProgress(currentSentenceIndex, currentWordIndex);
        // 创建金币动画
        const rect = feedbackElement.getBoundingClientRect();
        createCoinAnimation(rect.left + rect.width / 2, rect.top + rect.height / 2, () => {
            // 动画完成后增加分数
            score++;
            // 更新ProgressData中的积分 - 只增加1分
            ProgressData.updateScore(1);
            // 更新积分显示
            updateScoreDisplay();
            // 立即进入下一个单词
            goToNextItem();
        });
    }
}

// 开始句子练习
function startSentencePractice() {
    // 隐藏单词练习区域，显示句子练习区域
    wordPracticeSection.classList.add('hidden');
    sentencePracticeSection.classList.remove('hidden');

    const currentSentence = sentenceData[currentSentenceIndex].sentence;

    // 设置30秒学习计时器
    if (learningTimer) {
        clearTimeout(learningTimer);
    }
    learningTimer = setTimeout(() => {
        console.log('句子学习时间已达到30秒上限');
        // 记录学习时间已达上限，但不自动跳转
        if (typeof ProgressData !== 'undefined') {
            const sentenceId = sentenceData[currentSentenceIndex].id;
            ProgressData.updateSentenceRecord(sentenceId, false); // 标记为未完成
            // 注意：句子学习没有记录时长，仅记录完成状态
        }
        learningTimer = null;
    }, MAX_LEARNING_TIME);

    // 预加载下一个句子的音频资源
    preloadAudioResources();

    // 生成句子选项
    const allSentences = sentenceData.map(item => item.sentence);
    const sentenceOptions = generateSentenceOptions(currentSentence, allSentences);

    // 清空并生成选项UI
    sentenceOptionsContainer.innerHTML = '';
    sentenceOptions.forEach(sentence => {
        const optionElement = document.createElement('div');
        optionElement.className = 'option';
        optionElement.textContent = sentence;
        optionElement.addEventListener('click', () => checkSentenceAnswer(sentence));
        sentenceOptionsContainer.appendChild(optionElement);
    });

    // 自动播放当前句子音频
    playCurrentSentence();
}

// 检查句子答案
function checkSentenceAnswer(selectedSentence) {
    // 清除学习计时器
    if (learningTimer) {
        clearTimeout(learningTimer);
        learningTimer = null;
    }

    const currentSentence = sentenceData[currentSentenceIndex].sentence;
    const isCorrect = selectedSentence === currentSentence;
    
    // 记录学习事件
    if (typeof LearningStats !== 'undefined') {
        LearningStats.recordLearningEvent(isCorrect);
    }
    
    const sentenceId = sentenceData[currentSentenceIndex].id;

    // 播放音效
const audio = new Audio(isCorrect ? 'audio/word_correct.mp3' : 'audio/word_wrong.mp3');
if (!isCorrect) {
    // 禁用所有选项
    disableOptions(sentenceOptionsContainer);
}
new Promise((resolve) => {
    audio.addEventListener('ended', resolve, { once: true });
    audio.play().catch(e => {
        console.log('播放音效失败:', e);
        resolve();
    });
}).then(() => {
    if (!isCorrect) {
        // 音效播放完毕后播放错误句子发音
        // 直接使用句子查找ID
        const tempSentenceId = sentenceData.findIndex(s => s.sentence === selectedSentence) + 1;
        playAudioFile(`voice/sentences/sentence_${tempSentenceId}.mp3`, null, () => {
            // 发音结束后启用选项
            enableOptions(sentenceOptionsContainer);
    });
}
});
// 显示反馈
showFeedback(isCorrect);

// 高亮选中的选项
highlightSelectedOption(sentenceOptionsContainer, selectedSentence, isCorrect);

// 更新学习进度记录
ProgressData.updateSentenceRecord(sentenceId, isCorrect);

// 如果正确，增加分数
if (isCorrect) {
        // 禁用所有选项
        disableOptions(sentenceOptionsContainer);
        // 保存当前学习进度
        ProgressData.setCurrentProgress(currentSentenceIndex, currentWordIndex);
        // 创建金币动画
        const rect = feedbackElement.getBoundingClientRect();
        createCoinAnimation(rect.left + rect.width / 2, rect.top + rect.height / 2, () => {
            // 动画完成后增加分数
            score++;
            // 更新ProgressData中的积分 - 只增加1分
            ProgressData.updateScore(1);
            // 更新积分显示
            updateScoreDisplay();
            // 立即进入下一句
            goToNextItem();
        });
    }

    // 更新进度
    updateProgress();
}

// 显示反馈
function showFeedback(isCorrect) {
    feedbackElement.classList.remove('hidden', 'correct', 'incorrect');
    if (isCorrect) {
        feedbackElement.textContent = '正确！做得好！';
        feedbackElement.classList.add('correct');
    } else {
        feedbackElement.textContent = '不正确，请再试一次。';
        feedbackElement.classList.add('incorrect');
    }
}

// 高亮选中的选项
function highlightSelectedOption(container, selectedValue, isCorrect) {
    const options = container.getElementsByClassName('option');
    for (let option of options) {
        if (option.textContent === selectedValue) {
            option.classList.add(isCorrect ? 'correct' : 'incorrect');
            break;
        }
    }
}

// 禁用所有选项
function disableOptions(container) {
    const options = container.getElementsByClassName('option');
    for (let option of options) {
        // 通过设置pointer-events为none来禁止点击，比移除事件监听器更可靠
        option.style.pointerEvents = 'none';
        option.style.cursor = 'default';
    }
}

// 启用所有选项
function enableOptions(container) {
    const options = container.getElementsByClassName('option');
    for (let option of options) {
        option.style.pointerEvents = 'auto';
        option.style.cursor = 'pointer';
    }
}

// 更新进度条
function updateProgress() {
    const totalItems = sentenceData.length * 2; // 每个句子有单词和句子两个练习
    
    // 计算已完成的项目数
    let completedItems = currentSentenceIndex * 2; // 前面句子的所有练习
    
    // 如果当前句子的单词练习已完成
    if (currentWordIndex >= sentenceData[currentSentenceIndex].words.length - 1) {
        completedItems += 1; // 加1个单词练习
        
        // 如果句子练习也已完成
        if (!sentencePracticeSection.classList.contains('hidden')) {
            completedItems += 1; // 加1个句子练习
        }
    }
    
    const progressPercentage = (completedItems / totalItems) * 100;
    progressBar.style.width = `${progressPercentage}%`;
}

// 进入下一项练习
function goToNextItem() {
    // 隐藏反馈和下一步按钮
    feedbackElement.classList.add('hidden');
    nextBtn.classList.add('hidden');

    // 如果单词练习还没完成，继续下一个单词
    if (currentWordIndex < sentenceData[currentSentenceIndex].words.length - 1) {
        // 寻找下一个需要复习的单词
        let nextWordIndex = currentWordIndex + 1;
        const currentSentence = sentenceData[currentSentenceIndex];
        const now = Date.now();
        let foundReviewWord = false;

        console.log('===== 开始查找需要复习的单词 =====');
        console.log('当前单词索引:', currentWordIndex);
        console.log('当前时间:', new Date(now).toLocaleString());

        while (nextWordIndex < currentSentence.words.length) {
            const nextWord = currentSentence.words[nextWordIndex];
            const wordRecord = ProgressData.wordRecords[nextWord];

            console.log('检查单词:', nextWord);
            console.log('单词记录:', wordRecord);

            // 如果单词没有学习记录或者需要复习
            if (!wordRecord || wordRecord.nextReview <= now) {
                console.log('找到需要复习的单词:', nextWord);
                console.log('原因:', !wordRecord ? '没有学习记录' : `下次复习时间(${new Date(wordRecord.nextReview).toLocaleString()}) <= 当前时间`);
                currentWordIndex = nextWordIndex;
                foundReviewWord = true;
                break;
            } else {
                console.log('跳过不需要复习的单词:', nextWord);
                console.log('下次复习时间:', new Date(wordRecord.nextReview).toLocaleString());
            }
            nextWordIndex++;
        }

        // 如果找到了需要复习的单词，开始练习
        if (foundReviewWord) {
            startWordPractice();
        } else {
            // 如果当前句子中没有需要复习的单词，直接进入句子练习
            console.log('当前句子中没有需要复习的单词，进入句子练习');
            currentWordIndex = currentSentence.words.length - 1; // 设置为最后一个单词，触发句子练习
            startSentencePractice();
        }
    } else {
        // 如果单词练习已完成，开始句子练习
        if (sentencePracticeSection.classList.contains('hidden')) {
            startSentencePractice();
        } else {
            // 如果句子练习已完成，进入下一个句子
            currentWordIndex = 0;

            // 确定下一个要练习的句子
            if (reviewMode && reviewSentenceIds.length > 0) {
                // 从复习列表中获取下一个句子
                const nextSentenceId = reviewSentenceIds.shift();
                currentSentenceIndex = sentenceData.findIndex(s => s.id === nextSentenceId);
                
                // 如果复习列表为空，退出复习模式
                if (reviewSentenceIds.length === 0) {
                    reviewMode = false;
                }
            } else {
                // 正常模式下，进入下一个句子
            currentSentenceIndex++;
            // 检查下一个句子是否有需要复习的单词
            const nextSentence = sentenceData[currentSentenceIndex];
            if (nextSentence) {
                const now = Date.now();
                let hasReviewWord = false;
                for (const word of nextSentence.words) {
                    const wordRecord = ProgressData.wordRecords[word];
                    if (!wordRecord || wordRecord.nextReview <= now) {
                        hasReviewWord = true;
                        break;
                    }
                }
                // 如果下一个句子没有需要复习的单词，跳过
                if (!hasReviewWord) {
                    console.log('下一个句子没有需要复习的单词，跳过');
                    currentSentenceIndex++;
                    // 递归检查，确保找到有需要复习单词的句子
                    goToNextItem();
                    return;
                }
            }
                // 保存当前学习进度
                ProgressData.setCurrentProgress(currentSentenceIndex, currentWordIndex);
            }

            // 检查是否所有句子都已完成
            if (currentSentenceIndex >= sentenceData.length) {
                endPractice();
                return;
            }

            // 重置练习区域
            sentencePracticeSection.classList.add('hidden');
            wordPracticeSection.classList.remove('hidden');
            startWordPractice();
        }
    }
}

// 结束练习
function endPractice() {
    // 隐藏练习区域，显示最终得分
    wordPracticeSection.classList.add('hidden');
    sentencePracticeSection.classList.add('hidden');

    const totalQuestions = sentenceData.length * 2; // 每个句子有单词和句子两个练习
    const scorePercentage = (score / totalQuestions) * 100;

    let resultMessage = `练习完成！你的得分是 ${score}/${totalQuestions} (${scorePercentage.toFixed(1)}%)`;
    if (scorePercentage >= 80) {
        resultMessage += ' 太棒了！';
    } else if (scorePercentage >= 60) {
        resultMessage += ' 做得不错，继续努力！';
    } else {
        resultMessage += ' 加油，多练习会更好！';
    }

    feedbackElement.textContent = resultMessage;
    feedbackElement.classList.remove('hidden', 'correct', 'incorrect');

    // 显示重新开始按钮
    nextBtn.textContent = '重新开始';
    nextBtn.classList.remove('hidden');
    nextBtn.addEventListener('click', restartPractice);
}

// 重新开始练习
function restartPractice() {
    currentSentenceIndex = 0;
        currentWordIndex = 0;
        score = 0;
        // 重置ProgressData中的积分和学习进度
        ProgressData.resetScore();
        ProgressData.resetCurrentProgress();
    // 更新积分显示
    updateScoreDisplay();
    progressBar.style.width = '0%';
    feedbackElement.classList.add('hidden');
    nextBtn.textContent = '下一项';
    nextBtn.removeEventListener('click', restartPractice);
    wordPracticeSection.classList.remove('hidden');
    startWordPractice();
}

// 页面加载完成后初始化应用
window.addEventListener('DOMContentLoaded', initApp);